package com.xh.bussiness.exam.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.xh.bussiness.exam.bean.request.CurrDto;
import com.xh.bussiness.exam.bean.request.StudentExerciseRequest;
import com.xh.bussiness.exam.model.StudentExercise;
import com.xh.bussiness.exam.service.IExerciseService;
import com.xh.bussiness.exam.model.Exercise;
import com.xh.bussiness.exam.bean.request.ExerciseRequest;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.thirdapi.base.bean.dto.ThirdClassLessonDto;
import com.xh.bussiness.thirdapi.base.bean.request.QueryThirdClassLessonRequest;
import com.xh.bussiness.thirdapi.xuebang.dto.VO.XuebangResultVO;
import com.xh.bussiness.thirdapi.xuebang.dto.request.QueryXuebnagClassLessonRequest;
import com.xh.bussiness.thirdapi.xuebang.model.XuebangClassLesson;
import com.xh.bussiness.thirdapi.xuebang.service.IXuebangService;
import com.xh.bussiness.tms.service.IStudentAttendService;
import com.xh.core.bean.XhExportHeaderBean;
import com.xh.core.util.ObjectUtils;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RestController;
import com.xh.core.controller.BaseController;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 课堂练习记录表 前端控制器
 * </p>
 *
 * @author Pitt Cheung
 * @since 2021-08-26
 */
@RestController
@RequestMapping("/admin/exercise")
public class ExerciseController extends BaseController {

    @Autowired
    private IExerciseService exerciseService;
    @Autowired
    private IXuebangService xuebangService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStudentAttendService studentAttendService;

    /**
     * 分页数据查询
     *
     * @param page 分页对象
     * @param bean 查询条件Bean
     * @return
     */
    @PostMapping("/queryPage")
    public XhPage queryPage(XhPage page, ExerciseRequest bean) {
        page = exerciseService.queryExercisePage(page, bean);
        return page;
    }

    @PostMapping("/selectExercisePage")
    public XhPage selectExercisePage(XhPage page, ExerciseRequest bean) {
        page = exerciseService.selectExercisePage(page, bean);
        return page;
    }

    /**
     * 数据查询
     *
     * @param bean 查询条件Bean
     * @return
     */
    @PostMapping("/query")
    public AjaxResult query(ExerciseRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", exerciseService.queryExercise(bean));
    }

    /**
     * 导出全部
     *
     * @param bean
     * @return
     */
    @PostMapping(value = "/exportAll")
    public AjaxResult exportAll(ExerciseRequest bean, HttpServletRequest request) {
        try {
            LinkedHashMap<String, XhExportHeaderBean> exportHeaderBeans = new LinkedHashMap<>();
            //exportHeaderBeans.put("username",new XhExportHeaderBean("用户名"));
            //exportHeaderBeans.put("deleted",new XhExportHeaderBean("是否删除",ImmutableMap.of(0,"否",1,"是")));
            //exportHeaderBeans.put("createTime",new XhExportHeaderBean("创建时间","yyyy-MM-dd HH:mm:ss"));

            String downloadUrl = exerciseService.exportAll(request, exportHeaderBeans, bean, "queryExercisePage");
            if (downloadUrl != null) {
                return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", downloadUrl);
            } else {
                return new AjaxResult(AjaxResultConstant.Result.ERROR, "导出失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(AjaxResultConstant.Result.ERROR);
        }
    }

    /**
     * 新增和保存
     *
     * @param exercise 实体对象
     * @return
     */
    @PostMapping(value = "/saveOrUpdate")
    @Transactional
    public AjaxResult saveOrUpdate(@Validated Exercise exercise) {
        if (exercise.getId() == null) {
            exerciseService.insert(exercise);
        } else {
            exerciseService.update(exercise);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 添加课堂练习
     * @param exercise
     * @return com.xh.core.bean.AjaxResult
     * @author 赵文博
     * @date 2021/8/26 18:290
     **/
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Exercise exercise) {
        boolean flag = exerciseService.insert(exercise);
        return flag ? new AjaxResult(AjaxResultConstant.Result.SUCCESS) : new AjaxResult(AjaxResultConstant.Result.ERROR);
    }

    /**
     * 删除操作
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteById/{id}")
    @Transactional
    public AjaxResult deleteById(@PathVariable String id) {
        exerciseService.delete(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 批量删除操作
     *
     * @param ids
     * @return
     */
    @PostMapping("/batchDelete")
    @Transactional
    public AjaxResult batchDelete(String[] ids) {
        exerciseService.batchDelete(ids);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 获取课次，需要标记
     * @author 赵文博
     * @date 2021/9/4 17:46
     * @param request
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/getCurr")
    public AjaxResult getCurr(QueryThirdClassLessonRequest request) {
        String currentUserId = UserUtils.getCurrentUserId();
        User user = userService.getById(currentUserId);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "当前用户不存在");
        }
        //获取从指定开始时间（当前时间）一直到课程结束的课次
        List<ThirdClassLessonDto> lessonDtos = getTms(user,request);
        //获取已点名的课次
        List<String> currIds= studentAttendService.queryCurrId(request.getThirdClassId());
        //获取已评价的课次
        List<String> currIdsEvaluation = exerciseService.queryCurrIdsEvaluation(request.getThirdClassId());
        //取已经点名且未评价的课次
        List<String> reduce1 = currIds.stream().filter(item -> !currIdsEvaluation.contains(item)).collect(toList());
        List<CurrDto> currDtos = new ArrayList<>();
        for (ThirdClassLessonDto dto : lessonDtos){
            CurrDto currDto = new CurrDto();
            ObjectUtils.copyNonNullProperties(dto,currDto);
            currDto.setStatus(1);//默认不可评价
            if(reduce1.contains(currDto.getLessonId())){
                currDto.setStatus(0);
            }
            currDtos.add(currDto);
        }

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",currDtos);
    }

    /**
     * 获取从指定开始时间（当前时间）一直到课程结束的课次
     * @author 赵文博
     * @date 2021/9/4 17:13
     * @return java.util.List<com.xh.bussiness.thirdapi.base.bean.dto.ThirdClassLessonDto>
     **/
    private List<ThirdClassLessonDto> getTms(User user,QueryThirdClassLessonRequest request) {
        List<ThirdClassLessonDto> resultDatas = new ArrayList<>();
        //对接教务系统数据来源（主要查询班级排课数据：1：新舟TMS；2：飞鸿TMS；3:学邦TMS；4：校宝TMS；5：校管家TMS）
        QueryXuebnagClassLessonRequest xuebnagClassLessonRequest = new QueryXuebnagClassLessonRequest();
        xuebnagClassLessonRequest.setTeacherId(Integer.parseInt(user.getThirdId()));
        xuebnagClassLessonRequest.setCourseDateBegin(request.getCourseDateBegin());
//        xuebnagClassLessonRequest.setCourseDateEnd(request.getCourseDateEnd());
        if (StringUtils.isNotEmpty(request.getThirdClassId())) {
            xuebnagClassLessonRequest.setMiniClassId(Integer.parseInt(request.getThirdClassId()));
        }
        xuebnagClassLessonRequest.setPageSize(500);
        XuebangResultVO resultVO = xuebangService.queryXuebangClassLesson(xuebnagClassLessonRequest);

        if (resultVO != null && resultVO.getData() != null) {
            List<Object> datas = resultVO.getData().getDatas();
            if (CollectionUtil.isNotEmpty(datas)) {
                List<ThirdClassLessonDto> collect = datas.stream().map(itme -> {
                    XuebangClassLesson xuebangClassLesson = BeanUtil.toBean(itme, XuebangClassLesson.class);
                    ThirdClassLessonDto dto = ThirdClassLessonDto.builder()
                            .lessonId(xuebangClassLesson.getMiniClassCourseId().toString())
                            .lessonName(xuebangClassLesson.getMiniClassName())
                            .courseDate(xuebangClassLesson.getCourseDate())
                            .courseTime(xuebangClassLesson.getCourseTime())
                            .miniClassId(xuebangClassLesson.getMiniClassId() == null ? null : xuebangClassLesson.getMiniClassId().toString())
                            .miniClassName(xuebangClassLesson.getMiniClassName())
                            .teacherId(xuebangClassLesson.getTeacherId() == null ? null : xuebangClassLesson.getTeacherId().toString())
                            .teacherName(xuebangClassLesson.getTeacherName())
                            .build();
                    return dto;
                }).collect(toList());

                resultDatas.addAll(collect);
            }
        }
        return resultDatas;
    }
}


